import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


public class Main {

	/**
	 * @param args
	 * @throws JSONException 
	 */
	public static void main(String[] args) throws Exception {
		getNames("");
//		entries.get("entry");
	
//		long total = System.currentTimeMillis();
//		try {
//			// Run a java app in a separate system process
//			Process proc = Runtime.getRuntime().exec("java -jar youtube/runytd2.jar http://www.youtube.com/watch?v=locIxsfpgp4");
//////		
////			// Then retreive the process output
//			InputStream in = proc.getInputStream();
////			InputStream err = proc.getErrorStream();
//			JSONArray arr = new JSONArray();
//			
//			BufferedReader br = new BufferedReader(new InputStreamReader(in));
//			String inputLine;
//			String downloadedFile ="";
//			while ((inputLine = br.readLine()) != null){
//				System.out.println(inputLine);
//				if(inputLine.contains("download complete"))
//					downloadedFile = inputLine.split("to")[1].trim();
//			}
//			in.close();
//			
//			System.out.println(downloadedFile.split(regex));
//
////			Process proc2 = Runtime.getRuntime().exec("ffmpeg -i aaa.mp4 aaa.mp3");
////			InputStream in2 = proc2.getInputStream();
////			
////			BufferedReader br3 = new BufferedReader(new InputStreamReader(in2));
////			String inputLine3;
////			while ((inputLine3 = br3.readLine()) != null)
////				System.out.println(inputLine3);
////			in2.close();
//			
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		double time = ((System.currentTimeMillis() - total)/1000);
//		System.out.println("Total time: " + time + " sec.");

	}
	
	public static String getNames(String name) throws Exception {
		String searchRes = excuteGET("https://gdata.youtube.com/feeds/api/videos?q=Shape%20Of%20My%20Heart&orderby=published&start-index=1&max-results=20&orderby&v=2");
//		JSONObject entries = new JSONObject(searchRes);
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(searchRes));
        Document dom = builder.parse(is);
        NodeList entries = dom.getElementsByTagName("entry");
        for(int i=0; i<entries.getLength(); i++){
        	  Node title = ((Element)entries.item(i)).getElementsByTagName("title").item(0);
        	  System.out.println("Title: " + title.getTextContent());
        	  Element media = (Element)((Element)entries.item(i)).getElementsByTagName("media:group").item(0);
        	  Node id = media.getElementsByTagName("yt:videoid").item(0);
        	  System.out.println("Video id: " + id.getTextContent());
        	  Node duration = media.getElementsByTagName("yt:duration").item(0);
        	  System.out.println((float)Integer.parseInt(duration.getAttributes().item(0).getTextContent())/60);
        }
        return null;
	}
	
	 public static String excuteGET(String targetURL)
	  {
	    URL url;
	    HttpURLConnection connection = null;  
	    try {
	      //Create connection
	      url = new URL(targetURL);
	      connection = (HttpURLConnection)url.openConnection();
	      connection.setRequestMethod("GET");

	      //Get Response	
	      InputStream is = connection.getInputStream();
	      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	      String line;
	      StringBuffer response = new StringBuffer(); 
	      while((line = rd.readLine()) != null) {
	        response.append(line);
	        response.append('\r');
	      }
	      rd.close();
	      return response.toString();

	    } catch (Exception e) {

	      e.printStackTrace();
	      return null;

	    } finally {

	      if(connection != null) {
	        connection.disconnect(); 
	      }
	    }
	  }

}
